import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:ride_rex/net/common_global_url.dart';
import 'package:ride_rex/net/common_net.dart';
import 'package:ride_rex/route.dart';
import 'package:ride_rex/service/oss_service.dart';
import 'package:ride_rex/service/user_service.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../../../service/log_service.dart';
import '../../../ui/common_dialogs.dart';

class ApiUpdateInfo extends CommonApi {
  ApiUpdateInfo.updateAvatar(String avatarPath)
      : super(CommonGlobalUrl.updateAvatar, params: {'avatarPath': avatarPath});

  ApiUpdateInfo.update({String? birthday, String? country, String? nickname})
      : super(
          CommonGlobalUrl.updateUserInfo,
          params: {
            if (birthday.notEmpty) 'birthday': birthday,
            if (country.notEmpty) 'country': country,
            if (nickname.notEmpty) 'nickname': nickname,
          },
        );
}

class EditInfoLogic extends GetxController with OnceClick {
  final TextEditingController textEditingController = TextEditingController();

  String birth = '';
  String country = '';
  String filePath = '';
  List<String> countryList = [];

  @override
  void onReady() async {
    super.onReady();
    textEditingController.text = UserService.instance.notifierOfMineInfo.value.nickname ?? '';
    birth = UserService.instance.notifierOfMineInfo.value.birthday ?? '';
    country = UserService.instance.notifierOfMineInfo.value.country ?? '';
    await _getCountryList();
    update();
  }

  Future _getCountryList() async {
    try {
      String result = await rootBundle.loadString('assets/json/country.json');
      dynamic json = jsonDecode(result);
      if (json is List) {
        countryList = await CommonJson.getList(json, (json) => json['en']);
      }
    } catch (_) {}
  }

  @override
  void onClose() {
    textEditingController.dispose();
    super.onClose();
  }

  Future changeAvatar() async {
    LMLogManager.stat(page: 'editavatar');

    ActionBottomSheet.actionSheet(items: [
      ActionSheetConfig(
        text: 'Take Photo',
        onTap: () async {
          CommonPrivilegeStatus status = await CommonPrivilege.camera();
          if (!status.result) {
            CommonDialogs.twoButton(
              title: status.title,
              description: status.message,
              cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
              confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
              onConfirm: () => CommonPrivilege.openSettings(),
            );
            return;
          }
          AssetEntity? assetEntity = await ActionPicker.camera(locale: const Locale('en', 'US'));
          if (assetEntity == null) return;
          filePath = (await assetEntity.file)?.path ?? '';
          update();
        },
      ),
      ActionSheetConfig(
        text: 'Choose From Library',
        onTap: () async {
          CommonPrivilegeStatus status = await CommonPrivilege.photos();
          if (!status.result) {
            CommonDialogs.twoButton(
              title: status.title,
              description: status.message,
              cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
              confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
              onConfirm: () => CommonPrivilege.openSettings(),
            );
            return;
          }

          List<AssetEntity> list = await ActionPicker.assets() ?? [];
          if (list.isEmpty) return;
          filePath = (await list.first.file)?.path ?? '';
          update();
        },
      ),
    ]);
  }

  Future submit() async {
    startOnce(() async {
      if (filePath.notEmpty) await uploadAvatar();
      await ApiUpdateInfo.update(
        birthday: birth,
        country: country,
        nickname: textEditingController.text,
      ).post();
      await UserService.instance.getCacheMineInfoBean(true);
      Loading.dismiss();
      CommonRoute.close();
    });
  }

  Future uploadAvatar() async {
    OssResultBean? bean = await OssService.uploadFile(filePath);
    String filename = bean?.filename ?? '';
    if (filename.notEmpty) await ApiUpdateInfo.updateAvatar(filename).post();
  }
}
